package com.baijiaoxi.utils.video;

import com.baijiaoxi.common.utils.jdk.CMDUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class VideoHelper {

    /**
     * 获取视频长度，分辨率
     *
     * @param fullFilePath
     * @return
     * @throws Exception
     */
    public static VideoInfo processVideo(String fullFilePath) throws Exception {
        List<String> commend = new java.util.ArrayList<String>();
        commend.add("ffmpeg");
        commend.add("-i");
        commend.add(fullFilePath);
        VideoInfo videoInfo = VideoInfo.build();
        try {
            ProcessBuilder builder = new ProcessBuilder();
            builder.command(commend);
            builder.redirectErrorStream(true);
            Process p = builder.start();

            // 1. start
            BufferedReader buf = null; // 保存ffmpeg的输出结果流
            String line = null;
            // read the standard output

            buf = new BufferedReader(new InputStreamReader(p.getInputStream()));

            StringBuffer sb = new StringBuffer();
            while ((line = buf.readLine()) != null) {
                sb.append(line);
                continue;
            }
            p.waitFor();// 这里线程阻塞，将等待外部转换进程运行成功运行结束后，才往下执行
            // 1. end//
            String res = sb.toString();
            String regex = "(\\[[^\\]]*\\])";
            // 创建 Pattern 对象
            Pattern r2 = Pattern.compile(regex);
            // 现在创建 matcher 对象
            res = res.replace("(", "[").replace(")", "]");
            Matcher m2 = r2.matcher(res);
            while (m2.find()) {
                res = res.replace(m2.group(), "()");
            }
            String regexVideo = "Video: (.*?), (.*?), (.*?)[,\\s]";

            // 创建 Pattern 对象
            Pattern r = Pattern.compile(regexVideo);
            // 现在创建 matcher 对象
            Matcher m = r.matcher(res);

            if (m.find()) {
                videoInfo.setWidthAndHeigtht(m.group(3));
            }

            String regexDuration = "Duration: (.*?), start: (.*?), bitrate: (\\d*) kb\\/s";
            // 创建 Pattern 对象
            Pattern r1 = Pattern.compile(regexDuration);
            // 现在创建 matcher 对象
            Matcher m1 = r1.matcher(res);
            if (m1.find()) {
                videoInfo.setLength(m1.group(1));
            }
        } catch (Exception e) {
            // System.out.println(e);
            throw e;

        }
        return videoInfo;
    }

    /**
     * 视频截图
     *
     * @param fullFilePath
     * @param output
     * @return
     * @throws Exception
     */
    public static VideoInfo getVideoInfo(String fullFilePath, String output) throws Exception {
        VideoInfo videoInfo = processVideo(fullFilePath);
        String cmd = "ffmpeg -i " + fullFilePath + " -y -f image2 -ss 5 -t 0.001 -s " + videoInfo.getTargetWidth() + "x" + videoInfo.getTargetHeight() + " " + output;
        log.debug("videoInfo:{},cmd:{}", videoInfo, cmd);
        CMDUtil.runWithResult(cmd);
        return videoInfo;
    }
}
